package com.robert.maps.utils;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;

import com.robert.maps.utils.POI;

import android.util.Log;
import android.util.Xml;

public class KmlPullParser {

	// names of the XML tags
	static final String DESCRIPTION = "description";
	static final String DOCUMENT = "document";
	static final String PLACEMARK = "placemark";
	static final String NAME = "name";
	static final String POINT = "Point";
	static final String COORDINATES = "coordinates";
	static final String KML = "kml";
	private final String kmlSource;


	public KmlPullParser(String feedUrl) {
		try {
			//this.feedUrl = new URL(feedUrl);
			this.kmlSource = feedUrl;
		//} catch (MalformedURLException e) {
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private InputStream getInputStream() {
		try {
			//return feedUrl.openConnection().getInputStream();
			return new BufferedInputStream(new FileInputStream(kmlSource), 8192);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	public List<POI> parse() {
		List<POI> messages = null;
		XmlPullParser parser = Xml.newPullParser();
		try {
			// auto-detect the encoding from the stream
			parser.setInput(this.getInputStream(), null);
			int eventType = parser.getEventType();
			POI currentMessage = null;
			boolean done = false;
			while (eventType != XmlPullParser.END_DOCUMENT && !done){
				String name = null;
				switch (eventType){
					case XmlPullParser.START_DOCUMENT:
						messages = new ArrayList<POI>();
						break;
					case XmlPullParser.START_TAG:
						name = parser.getName();
						if (name.equalsIgnoreCase(PLACEMARK)){
							currentMessage = new POI();
						} else if (currentMessage != null){
							if (name.equalsIgnoreCase(NAME)){
								currentMessage.setName(parser.nextText());
							} else if (name.equalsIgnoreCase(DESCRIPTION)){
								currentMessage.setDescription(parser.nextText());
							} else if (name.equalsIgnoreCase(COORDINATES)){
								currentMessage.setGeoPoint(parser.nextText());
							} 
						}
						break;
					case XmlPullParser.END_TAG:
						name = parser.getName();
						if (name.equalsIgnoreCase(PLACEMARK) && currentMessage != null){
							messages.add(currentMessage);
						} else if (name.equalsIgnoreCase(KML)){
							done = true;
						}
						break;
				}
				eventType = parser.next();
			}
		} catch (Exception e) {
			Log.e("AndroidNews::PullFeedParser", e.getMessage(), e);
			throw new RuntimeException(e);
		}
		return messages;
	}
}
